package com.zhr.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

public class Encrypter {

	private String timestamp;

	private String nonce;

	private String signature;

	private String echostr;

	private String token;

	public Encrypter(String token, Map<String, String> params) {
		super();
		this.token = token;
		this.timestamp = params.get("timestamp");
		this.nonce = params.get("nonce");
		this.signature = params.get("signature");
		this.echostr = params.get("echostr");
	}

	public Encrypter(String token, String timestamp, String nonce,
			String signature, String echostr) {
		super();
		this.token = token;
		this.timestamp = timestamp;
		this.nonce = nonce;
		this.signature = signature;
		this.echostr = echostr;
	}

	public boolean validate() {
		try {
			String arrays[] = new String[] { token, timestamp, nonce };
			Arrays.sort(arrays);
			String result = join(arrays);
			return signature.equals(encrypt(result, "SHA-1"));
		} catch (Exception e) {
			return false;
		}
	}

	private String encrypt(String strSrc, String encName) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	private String join(String... strs) {
		String result = "";
		for (String string : strs) {
			result += string;
		}
		return result;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getNonce() {
		return nonce;
	}

	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public String getEchostr() {
		return null == echostr ? "" : echostr;
	}

	public void setEchostr(String echostr) {
		this.echostr = echostr;
	}

}
